package cn.s1995.sloth.bizs.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.s1995.sloth.bizs.constant.CacheNames;
import cn.s1995.sloth.bizs.entity.UserHistorySearch;
import cn.s1995.sloth.bizs.mapper.UserHistorySearchMapper;
import cn.s1995.sloth.bizs.service.UserHistorySearchService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
/**
 * 用户历史搜索
 *
 * @author sloth
 * @date 2023-12-27 09:11:34
 */
@Service
public class UserHistorySearchServiceImpl extends ServiceImpl<UserHistorySearchMapper, UserHistorySearch> implements UserHistorySearchService {

	@Override
	@Async
	public void updateHistory(Long uid, String search) {
		UserHistorySearch old = this.getOne(
				Wrappers.lambdaQuery(UserHistorySearch.class)
						.eq(UserHistorySearch::getUid, uid)
						.eq(UserHistorySearch::getContent, search)
			);
		if(ObjectUtil.isNotNull(old)) {
			//更新时间
			this.updateById(old);
		}else {
			//保存
			this.save(
				UserHistorySearch.builder()
								.uid(uid)
								.content(search)
								.build()
			);
		}
	}

	@Override
	@Cacheable(value = CacheNames.userHistorySearchPopular)
	public List<String> getPopularSearch() {
		QueryWrapper<UserHistorySearch> wrapper = new QueryWrapper<UserHistorySearch>();
		wrapper.select("content,COUNT(uid) AS num")
			   	.groupBy("content")
			   	.orderByDesc("num")
			   	.last(" LIMIT 10");
		List<UserHistorySearch> list = this.list(wrapper);
		if(ObjectUtil.isNotEmpty(list)) {
			return list.stream().map(e -> e.getContent()).collect(Collectors.toList());
		}
		return Collections.emptyList();
	}
}
